package com.lwl.concurrency.synchr;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 无论是内部synchronized还是ReenterLock,一次都只允许一个线程 访问一个资源,而信号量却可以指定多个线程同时访问某一个资源
 * 
 * @author bruce - 2018/03/27 22:00:16
 */
public class SemaphoreTest {
	final Semaphore semp = new Semaphore(5);

	public void run() {
		try {
			System.out.println(Thread.currentThread().getName() + ":acquire...");
			semp.acquire();
			System.out.println(Thread.currentThread().getName() + ":acquire success...");
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			semp.release();
			System.out.println(Thread.currentThread().getName() + ":release...");
		}
	}

	public static void main(String[] args) {
		ExecutorService threadPool = Executors.newFixedThreadPool(20);
		SemaphoreTest demo = new SemaphoreTest();
		for (int i = 0; i < 20; i++) {
			threadPool.submit(demo::run);
		}
	}

}
